<template>
  <div>
    <van-nav-bar
      title="城市列表"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <div class="bottom">
      <van-index-bar :index-list="indexList" sticky>
        <div v-for="(item, key) in allObj" :key="key">
          <van-index-anchor :index="key">
            <span v-if="key === '#'" style="color: #777; font-size: 10px"
              >当前城市</span
            >
            <span v-else-if="key === '热'" style="color: #777; font-size: 10px"
              >热门城市</span
            >
            <span v-else style="color: #777; font-size: 10px">{{ key }}</span>
          </van-index-anchor>
          <van-cell
            @click="onClick(item1)"
            :title="item1.label"
            v-for="(item1, index) in item"
            :key="index"
          />
        </div>
      </van-index-bar>
    </div>
  </div>
</template>

<script>
import { getCitys, getHotCitys } from '@/api/HomePageajax'
export default {
  name: 'citylist-page',
  data() {
    return {
      indexList: [],
      allObj: {}
    }
  },
  methods: {
    onClick(city) {
      window.localStorage.setItem('city', JSON.stringify(city))
      this.$router.push('/homepage')
    }
  },
  async created() {
    const res1 = await getHotCitys()
    const res2 = await getCitys({ level: 1 })
    // 在ascii看来 $和#都是排在前面 这个顺序不会乱
    // arr.sort()默认就是按ascii排
    const allObj = {
      '#': [
        {
          label: '上海',
          value: 'AREA|dbf46d32-7e76-1196',
          pinyin: 'shanghai',
          short: 'sh'
        }
      ],
      热: res1.body,
      A: [],
      B: [],
      C: [],
      D: [],
      E: [],
      F: [],
      G: [],
      H: [],
      I: [],
      J: [],
      K: [],
      L: [],
      M: [],
      N: [],
      O: [],
      P: [],
      Q: [],
      R: [],
      S: [],
      T: [],
      U: [],
      V: [],
      W: [],
      X: [],
      Y: [],
      Z: []
    }

    res2.body.forEach((item) => {
      const key = item.short[0].toUpperCase()
      allObj[key].push(item)
    })

    // 遍历allObj,把所有的值是空数组的这一项属性移除掉
    for (const key in allObj) {
      if (allObj[key].length === 0) {
        delete allObj[key]
      }
    }
    console.log(allObj)
    this.indexList = Object.keys(allObj)
    this.allObj = allObj
  }
}
</script>

<style scoped lang="less">
::v-deep .van-index-bar__index {
  margin: 6px 0;
}

.bottom {
  position: fixed;
  top: 45px;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: auto;
}
::v-deep .van-nav-bar__content {
  background-color: #21b97a !important;
}
::v-deep .van-nav-bar__title {
  color: aliceblue !important;
}
::v-deep .van-icon-arrow-left {
  color: aliceblue !important;
}
</style>
